package com.zheng.common.validator;

import com.baidu.unbiz.fluentvalidator.ValidationError;
import com.baidu.unbiz.fluentvalidator.Validator;
import com.baidu.unbiz.fluentvalidator.ValidatorContext;
import com.baidu.unbiz.fluentvalidator.ValidatorHandler;

import java.math.BigDecimal;

/**
 * 长度校验
 * Created by shuzheng on 2017/2/18.
 */
public class DecimalValidator extends ValidatorHandler<BigDecimal> implements Validator<BigDecimal> {

    private int min;

    private int max;

    private String fieldName;

    public DecimalValidator(int min, int max, String fieldName) {
        this.min = min;
        this.max = max;
        this.fieldName = fieldName;
    }

    @Override
    public boolean validate(ValidatorContext context, BigDecimal price) {
        if(null != price){
            int length = price.toString().replace(".", "").length();
            if (length > max ||length < min) {
                context.addError(ValidationError.create(String.format("%s长度必须介于%s~%s之间！", fieldName, min, max))
                        .setErrorCode(-1)
                        .setField(fieldName)
                        .setInvalidValue(price));
                return false;
            }
            if (price.compareTo(new BigDecimal(0)) < 0) {
                context.addError(ValidationError.create(String.format("输入%s的值必须大于0！", fieldName))
                        .setErrorCode(-1)
                        .setField(fieldName)
                        .setInvalidValue(price));
                return false;
            }
            return true;
        }
        context.addError(ValidationError.create(String.format("%s不能为空！！", fieldName))
                .setErrorCode(-1)
                .setField(fieldName)
                .setInvalidValue(price));
        return false;
    }

}
